package com.acwing.partition3;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/12/12 9:27
 */
public class AC272最长公共上升子序列 {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] s = reader.readLine().split("\\s+");
        int n = Integer.parseInt(s[0]);
        int[] nums1 = new int[n], nums2 = new int[n];
        s = reader.readLine().split("\\s+");
        for (int i = 0; i < n; i++) nums1[i] = Integer.parseInt(s[i]);
        s = reader.readLine().split("\\s+");
        for (int i = 0; i < n; i++) nums2[i] = Integer.parseInt(s[i]);
        writer.write(String.valueOf(dynamicProgramming(nums1, nums2)));
        writer.flush();
    }

    private static int dynamicProgramming(int[] nums1, int[] nums2) {
        //LCS：f[i][j]=max(f[i][j],f[i−1][j−1]+1) (i,j>0,a[i]=b[j])，f[i][j]=max(f[i][j−1],f[i−1][j]) (i,j>0,a[i]≠b[j])
        //LIS：f[i]=max(f[i],f[j]+1) (j<i,a[j]<a[i])
        //LCIS：设f[i][j]代表的是a序列前i个元素与b序列前j个元素的LCIS长度，t为最长LCIS的结尾元素位置
        // f[i][j]=f[i−1][j] (a[i]≠b[j])，f[i][j]=max(f[i−1][j],f[i−1][t]+1) (a[i]=b[j])
        int n = nums1.length, answer = 0;
        int[][] dp = new int[n + 1][n + 1];
        for (int i = 1; i <= n; i++) {
            int max = 1;
            for (int j = 1; j <= n; j++) {
                dp[i][j] = dp[i - 1][j];
                if (nums1[i - 1] == nums2[j - 1]) dp[i][j] = Math.max(dp[i][j], max);
                else if (nums1[i - 1] > nums2[j - 1]) max = Math.max(max, dp[i - 1][j] + 1);
            }
        }
        for (int i = 1; i <= n; i++) answer = Math.max(answer, dp[n][i]);
        return answer;
    }
}
